package com.party.admin.biz.crowdfund;

import com.alibaba.druid.support.json.JSONUtils;
import com.google.common.base.Function;
import com.google.common.collect.Maps;
import com.party.admin.biz.activity.ActivityBizService;
import com.party.admin.biz.copartner.MemberCopartnerDetailBizService;
import com.party.admin.biz.file.FileBizService;
import com.party.admin.biz.merchantAnalyze.MemberMerchantDetailBizService;
import com.party.admin.biz.system.MemberBizService;
import com.party.admin.biz.webSocket.WebSocketBizService;
import com.party.admin.redisPubSub.publish.RedisMsgPublish;
import com.party.admin.redisPubSub.subscribe.SubScribeMessage;
import com.party.admin.utils.RealmUtils;
import com.party.admin.web.dto.output.crowdfund.ProjectForActivityOutput;
import com.party.admin.web.dto.output.crowdfund.ProjectPosterOutput;
import com.party.common.constant.Constant;
import com.party.common.paging.Page;
import com.party.common.utils.*;
import com.party.core.exception.BusinessException;
import com.party.core.model.YesNoStatus;
import com.party.core.model.activity.ActStatus;
import com.party.core.model.activity.Activity;
import com.party.core.model.counterfoil.Counterfoil;
import com.party.core.model.counterfoil.CounterfoilBusiness;
import com.party.core.model.crowdfund.*;
import com.party.core.model.distributor.DistributorCount;
import com.party.core.model.distributor.DistributorDetail;
import com.party.core.model.distributor.DistributorRelation;
import com.party.core.model.member.Member;
import com.party.core.model.member.MemberAct;
import com.party.core.model.member.MemberGroup;
import com.party.core.model.member.PartnerMember;
import com.party.core.model.system.RoleEnum;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.cos.CosBizService;
import com.party.core.service.counterfoil.ICounterfoilBusinessService;
import com.party.core.service.counterfoil.ICounterfoilService;
import com.party.core.service.crowdfund.*;
import com.party.core.service.distributor.IDistributorCountService;
import com.party.core.service.distributor.IDistributorDetailService;
import com.party.core.service.distributor.IDistributorRelationService;
import com.party.core.service.goods.IGoodsCouponsService;
import com.party.core.service.member.IMemberActService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.member.IMemberService;
import com.party.core.service.member.IPartnerMemberService;
import com.party.core.service.member.biz.MemberPersonalCountBizService;
import com.party.core.service.order.IOrderFormService;
import com.party.core.service.system.ISysRoleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 众筹项目业务接口
 * Created by wei.li
 *
 * @date 2017/7/10 0010
 * @time 15:04
 */
@Service
public class ProjectBizService {

    @Autowired
    private IProjectService projectService;

    @Autowired
    private ISupportService supportService;

    @Autowired
    private IDistributorDetailService distributorDetailService;

    @Autowired
    private IDistributorCountService distributorCountService;

    @Autowired
    private IActivityService activityService;

    @Autowired
    private ITargetProjectService targetProjectService;

    @Autowired
    private IMemberActService memberActService;

    @Autowired
    private SupportBizService supportBizService;

    @Autowired
    private IAnalyzeService analyzeService;

    @Autowired
    private FileBizService fileBizService;

    @Autowired
    private CosBizService cosBizService;

    @Autowired
    private MemberPersonalCountBizService memberPersonalCountBizService;

    @Autowired
    private IProjectApplyService projectApplyService;

    @Autowired
    private MemberMerchantDetailBizService memberMerchantDetailBizService;

    @Autowired
    private MemberCopartnerDetailBizService memberCopartnerDetailBizService;

    @Autowired
    private IMemberService memberService;

    @Autowired
    private RedisMsgPublish redisMsgPublish;

    @Autowired
    private WebSocketBizService webSocketBizService;

    @Autowired
    private IGoodsCouponsService goodsCouponsService;

    @Autowired
    private IPartnerMemberService partnerMemberService;

    @Autowired
    private IProjectContentService projectContentService;

    @Autowired
    private IProjectDetailCountService projectDetailCountService;

    @Autowired
    private IProjectBrokerageService projectBrokerageService;

    @Autowired
    private IProjectLabelService projectLabelService;

    @Autowired
    private IProjectCommentService projectCommentService;

    @Autowired
    private ICrowdfundRankService crowdfundRankService;

    @Autowired
    private ISupportTransferService supportTransferService;

    @Autowired
    private IDistributorRelationService distributorRelationService;

    @Autowired
    private ActivityBizService activityBizService;

    @Autowired
    private IOrderFormService orderFormService;

    @Autowired
    private ICrowdfundEventService crowdfundEventService;

    @Autowired
    private ICounterfoilBusinessService counterfoilBusinessService;

    @Autowired
    private ICounterfoilService counterfoilService;

    @Value("#{party['mic.url']}")
    private String micUrl;

    @Value("#{party['userfiles.basedir']}")
    private String baseDir;

    @Autowired
    private PaintProjectPosterBiz paintProjectPosterBiz;

    @Autowired
    private IEventGradationService eventGradationService;

    @Autowired
    private IProjectGradationService projectGradationService;

    @Autowired
    private IMemberGroupService memberGroupService;

    @Autowired
    private ISysRoleService sysRoleService;

    protected static Logger logger = LoggerFactory.getLogger(ProjectBizService.class);


    /**
     * 查询活动下的众筹
     *
     * @param isSuccess 是否筹集成功
     * @param targetId  目标编号
     * @param page      分页参数
     * @return 众筹列表
     */
    public List<ProjectForActivityOutput> projectForActivityList(boolean isSuccess, String targetId, Page page) {
        ProjectWithAuthor projectWithAuthor = new ProjectWithAuthor();

        // 众筹成功？
        Integer success = isSuccess ? 1 : 0;
        projectWithAuthor.setIsSuccess(success);
        projectWithAuthor.setTargetId(targetId);
        List<ProjectWithAuthor> projectWithAuthorList = projectService.listPage(projectWithAuthor, page);
        List<ProjectForActivityOutput> projectForActivityOutputList = LangUtils.transform(projectWithAuthorList,
                new Function<ProjectWithAuthor, ProjectForActivityOutput>() {
                    public ProjectForActivityOutput apply(ProjectWithAuthor projectWithAuthor) {
                        return ProjectForActivityOutput.transform(projectWithAuthor);
                    }
                });
        return projectForActivityOutputList;
    }

    @Autowired
    private MemberBizService memberBizService;

    /**
     * 查询活动下的众筹
     *
     * @param projectWithAuthor 众筹信息
     * @param page              分页参数
     * @return 众筹列表
     */
    public List<ProjectForActivityOutput> projectForActivityList(ProjectWithAuthor projectWithAuthor, Page page) {
        String memberId = RealmUtils.getCurrentUser().getId();
        Integer isMultiple = StringUtils.isNotEmpty(projectWithAuthor.getCurrentGradation()) ? YesNoStatus.YES.getCode() : YesNoStatus.NO.getCode();
        projectWithAuthor.setDistribution(true);
        List<ProjectWithAuthor> projectWithAuthorList = projectService.listPage(projectWithAuthor, page);
        List<ProjectForActivityOutput> projectForActivityOutputList
                = LangUtils.transform(projectWithAuthorList,
                new Function<ProjectWithAuthor, ProjectForActivityOutput>() {
                    @Override
                    public ProjectForActivityOutput apply(ProjectWithAuthor projectWithAuthor) {
                        //替换手机号
                        String phone = memberBizService.replacePhone(memberId, projectWithAuthor.getAuthorMobile());
                        projectWithAuthor.setAuthorMobile(phone);

                        ProjectForActivityOutput output = transform(projectWithAuthor);
                        String filePath = fileBizService.getUploadCIPath("crowdfund", projectWithAuthor.getAuthorId());
                        String qrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + projectWithAuthor.getId());
                        String url = getUrl(projectWithAuthor.getId(), isMultiple);
                        output.setQrCodeUrl(qrCodeUrl);
                        output.setUrl(url);
                        return output;
                    }
                });
        return projectForActivityOutputList;
    }

    /**
     * 查询活动下的众筹
     *
     * @param projectWithAuthor 众筹信息
     * @param page              分页参数
     * @return 众筹列表
     */
    public List<ProjectForActivityOutput> projectForActivityList(ProjectWithAuthor projectWithAuthor,
                                                                 Page page, String publisher) {
        String memberId = RealmUtils.getCurrentUser().getId();
        Integer isMultiple = StringUtils.isNotEmpty(projectWithAuthor.getCurrentGradation()) ? YesNoStatus.YES.getCode() : YesNoStatus.NO.getCode();
        projectWithAuthor.setDistribution(true);
        List<ProjectWithAuthor> projectWithAuthorList = projectService.listPage(projectWithAuthor, page);
        List<ProjectForActivityOutput> projectForActivityOutputList
                = LangUtils.transform(projectWithAuthorList,
                new Function<ProjectWithAuthor, ProjectForActivityOutput>() {

                    @Override
                    public ProjectForActivityOutput apply(ProjectWithAuthor projectWithAuthor) {
                        //替换手机号
                        String phone = memberBizService.replacePhone(memberId, projectWithAuthor.getAuthorMobile());
                        projectWithAuthor.setAuthorMobile(phone);

                        ProjectForActivityOutput output = transform(projectWithAuthor);
                        String filePath = fileBizService.getUploadCIPath("crowdfund", projectWithAuthor.getAuthorId());
                        String qrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + projectWithAuthor.getId());
                        String url = getUrl(projectWithAuthor.getId(), isMultiple);
                        output.setQrCodeUrl(qrCodeUrl);
                        output.setUrl(url);
                        return output;
                    }
                });
        return projectForActivityOutputList;
    }

    /**
     * 根据分销关系查询众筹项目
     *
     * @param relationId 分销关系
     * @param page       分页参数
     * @return 输出视图
     */
    public List<ProjectForActivityOutput> listForDistributorId(String relationId, Page page) {
        String memberId = RealmUtils.getCurrentUser().getId();

        ProjectWithAuthor projectWithAuthor = new ProjectWithAuthor();
        projectWithAuthor.setRelationId(relationId);
        List<ProjectWithAuthor> projectWithAuthorList = projectService.listPage(projectWithAuthor, page);
        List<ProjectForActivityOutput> projectForActivityOutputList
                = LangUtils.transform(projectWithAuthorList,
                new Function<ProjectWithAuthor, ProjectForActivityOutput>() {
                    public ProjectForActivityOutput apply(ProjectWithAuthor projectWithAuthor) {
                        //替换手机号
                        String phone = memberBizService.replacePhone(memberId, projectWithAuthor.getAuthorMobile());
                        projectWithAuthor.setAuthorMobile(phone);

                        return transform(projectWithAuthor);
                    }
                });
        return projectForActivityOutputList;
    }

    /**
     * 根据分销关系查询众筹项目
     *
     * @param
     * @param page 分页参数
     * @return 输出视图
     */
    public List<ProjectForActivityOutput> copartnerCrowList(ProjectWithAuthor projectWithAuthor, Page page) {
        List<ProjectWithAuthor> projectWithAuthorList = projectService.listForDistributorId(projectWithAuthor, page);
        List<ProjectForActivityOutput> projectForActivityOutputList
                = LangUtils.transform(projectWithAuthorList,
                projectWithAuthor1 -> transform(projectWithAuthor1));
        return projectForActivityOutputList;
    }

    /**
     * 转换输出视图
     *
     * @param projectWithAuthor 众筹信息
     * @return 输出视图
     */
    public ProjectForActivityOutput transform(ProjectWithAuthor projectWithAuthor) {
        ProjectForActivityOutput projectForActivityOutput = ProjectForActivityOutput.transform(projectWithAuthor);
        if (projectWithAuthor.getIsSuccess().equals(0)) {
            projectForActivityOutput.setStatus("众筹中");
        } else if (projectForActivityOutput.getIsSuccess().equals(1)) {
            projectForActivityOutput.setStatus("众筹成功");
        } else if (projectForActivityOutput.getIsSuccess().equals(2)) {
            projectForActivityOutput.setStatus("众筹失败");
        } else if (projectForActivityOutput.getIsSuccess().equals(3)) {
            projectForActivityOutput.setStatus("退款中");
        } else if (projectForActivityOutput.getIsSuccess().equals(4)) {
            projectForActivityOutput.setStatus("退款成功");
        }
        return projectForActivityOutput;
    }

    /**
     * 众筹退款
     *
     * @param id 众筹编号
     */
    public void refund(String id, String sessionId) {
        Project project = projectService.get(id);
        this.refund(project, sessionId);
    }


    /**
     * 众筹退款
     *
     * @param project 众筹
     */
    public void refund(Project project, String sessionId) {

        TargetProject targetProject = targetProjectService.findByProjectId(project.getId());

        // 更新报名状态
        MemberAct memberAct = memberActService.findByOrderId(targetProject.getOrderId());
        if (memberAct != null) {
            memberAct.setCheckStatus(ActStatus.ACT_STATUS_CANCEL.getCode());
            memberActService.update(memberAct);
        }
        project.setIsSuccess(Constant.CROWDFUND_PROJECT_REFUNDING);
        projectService.update(project);

        List<SupportWithMember> supportList = supportService.findByProjectId(project.getId());
        int needRefundNum = 0;
        for (SupportWithMember supportWithMember : supportList) {
            // 先改掉每一个支持的支付状态为退款中
            try {
                Support support = supportService.get(supportWithMember.getId());
                if (null == support) {
                    throw new BusinessException("支持信息不存在");
                }
                // 只有是支付成功和退款失败的才改 为退款中
                if (!Integer.valueOf(1).equals(support.getPayStatus()) && !Constant.SUPPORT_PAY_STATUS_FAIL.equals(support.getPayStatus())) {
                    continue;
                }
                needRefundNum++;
                support.setPayStatus(Constant.SUPPORT_PAY_STATUS_REFUNDING);
                supportService.update(support);
            } catch (Exception e) {
                logger.error("更改支持的支付状态为退款中失败", e);
            }
        }
        if (needRefundNum <= 0) {
            Map<String, String> jsonMap = Maps.newHashMap();
            String message = "不能进行退款, 没有订单的状态为\"支付成功\"或\"退款失败\"";
            jsonMap.put("memberId", RealmUtils.getCurrentUser().getId());
            jsonMap.put("sessionId", sessionId);
            jsonMap.put("message", message);
            String param = JSONUtils.toJSONString(jsonMap);
            redisMsgPublish.publish(SubScribeMessage.CHANNEL_NAME, param);
            return;
        }
        for (SupportWithMember supportWithMember : supportList) {
            Support support = supportService.get(supportWithMember.getId());
            if (null == support) {
                throw new BusinessException("支持信息不存在");
            }
            if (!Constant.SUPPORT_PAY_STATUS_REFUNDING.equals(support.getPayStatus())) {
                continue;
            }
            if (null == sessionId) {
                supportBizService.sendRefund(supportWithMember.getProjectId());
            } else {
                supportBizService.sendRefundWithMemberId(supportWithMember.getId(), RealmUtils.getCurrentUser().getId(), sessionId);
            }

        }
    }

    /**
     * 删除众筹
     *
     * @param id 众筹编号
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean delete(String id) {
        boolean endResult = true;
        String memberId = null;
        try {
            if (StringUtils.isEmpty(id)) {
                endResult = false;
                return endResult;
            }
            Project project = projectService.get(id);
            if (project == null) {
                endResult = false;
                return endResult;
            }
            Double actualAmount = supportService.countAll(null, id);
            if (actualAmount > Double.valueOf(0.0d)) {
                endResult = false;
                return endResult;
            }
            memberId = project.getAuthorId();
            //删除分销信息
            DistributorDetail distributorDetail = distributorDetailService.findByTargetId(id);
            if (null != distributorDetail) {
                DistributorCount distributorCount
                        = distributorCountService.findByRelationId(distributorDetail.getDistributorRelationId());
                if (null != distributorCount) {
                    distributorCount.setCrowdfundNum(distributorCount.getCrowdfundNum() - 1);
                    distributorCount.setApplyNum(distributorCount.getApplyNum() - 1);
                    distributorCountService.update(distributorCount);
                }
                DistributorRelation distributorRelation = distributorRelationService.get(distributorDetail.getDistributorRelationId());
                if (null != distributorRelation) {
                    memberCopartnerDetailBizService.updateApplyNumSub(distributorRelation, project.getCreateDate());
                }
                distributorDetailService.delete(distributorDetail.getId());
            }

            //众筹关系
            TargetProject targetProject = targetProjectService.findByProjectId(id);
            if (null != targetProject) {

                //修改众筹项目
                Activity activity = activityService.get(targetProject.getTargetId());
                if (Constant.IS_CROWFUND_ING.equals(project.getIsSuccess())) {
                    activity.setBeCrowdfundNum(activity.getBeCrowdfundNum() - 1 < 0 ? 0 : activity.getBeCrowdfundNum() - 1);
                }
                activity.setJoinNum(activity.getJoinNum() - 1 < 0 ? 0 : activity.getJoinNum() - 1);
                activityService.update(activity);

                //删除报名记录
                MemberAct memberAct = memberActService.findByOrderId(targetProject.getOrderId());
                if (memberAct != null) {
                    // 核销码
                    goodsCouponsService.deleteByOrderId(memberAct.getOrderId());
                    memberActService.delete(memberAct.getId());
                }
                targetProjectService.deleteLogic(targetProject.getId());

                // 数据分析
                projectLabelService.deleteByProjectId(id);

                try {
                    PartnerMember partnerMember = partnerMemberService.findByPartnerAndMember(activity.getMember(), project.getAuthorId());
                    memberPersonalCountBizService.countOne(partnerMember);
                } catch (Exception e) {
                    logger.error("实时更新个人统计众筹数量异常", e);
                }
                // 删除众筹内容
                ProjectContent projectContent = projectContentService.get(project.getContentId());
                if (projectContent != null) {
                    projectContentService.delete(projectContent.getId());
                }

                // 众筹详情统计-数据分析
                projectDetailCountService.deleteByProjectId(id);

                // 众筹评论
                projectCommentService.deleteByRefId(id);

                // 众筹排名
                crowdfundRankService.deleteByProjectId(id);
            }

            //删除票据报名关系，修改票据报名数量
            CounterfoilBusiness counterfoilBusiness = counterfoilBusinessService.findByBusinessId(id);
            if (null != counterfoilBusiness) {
                Counterfoil counterfoil = counterfoilService.get(counterfoilBusiness.getCounterfoilId());
                if (null != counterfoil) {
                    counterfoil.setJoinNum(counterfoil.getJoinNum() - 1);
                    counterfoilService.update(counterfoil);
                }
                counterfoilBusinessService.deleteByBusinessId(id);
            }


            Analyze analyze = analyzeService.findByTargetId(id);
            if (null != analyze) {
                analyzeService.delete(analyze.getId());
            }

            //删除众筹
            projectService.deleteLogic(id);
        } catch (Exception e) {
            endResult = false;
            logger.error("删除众筹失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        } finally {
            if (endResult) {
                try {
                    String filePath = fileBizService.getUploadCIPath("crowdfund", memberId);
                    String cosFilePath = CosBizService.getDeleteQrCodePath(filePath, id);
                    cosBizService.deleteFile(cosFilePath);
                } catch (Exception e) {
                    logger.error("删除众筹二维码失败", e);
                }
            }
        }
        return endResult;
    }

    /**
     * 众筹同步列表
     */
    public void synchronization() {
        List<Project> projectList = projectService.list(new Project());
        for (Project project : projectList) {
            Float sum = supportService.sumByProjectId(project.getId());
            sum = null == sum ? 0f : sum;
            project.setRealTimeAmount(sum);
            projectService.update(project);
        }
    }

    /**
     * 初始化最后支持数据
     */
    public void initLastSupportDate() {
        Project project = new Project();
        List<Project> projects = projectService.list(project);
        for (Project p : projects) {
            //获取最后的支持时间

            Date lastDate = supportService.getLastSupportDate(p.getId());

            //更新对应的字段
            if (lastDate != null) {

                //存在支持者
                project.setId(p.getId());
                project.setLastSupportDate(lastDate);
                projectService.update(project);
            }
        }
    }

    /**
     * 访问url
     *
     * @param projectId 项目编号
     * @return 访问链接
     */
    public String getUrl(String projectId, Integer isMultiple) {
        String content = "project/project_detail.html?id=" + projectId;
        if (null != isMultiple && YesNoStatus.YES.getCode().equals(isMultiple)) {
            content = "project/project_multi_detail.html?id=" + projectId;
        }
        return micUrl + content;
    }

    /**
     * 访问 直接付款众筹 链接 url
     *
     * @param projectId 项目编号
     * @return 访问链接
     */
    public String getDirectPayUrl(String projectId) {
        String content = "project/direct_detail.html?id=" + projectId;
        return micUrl + content;
    }

    /**
     * 更新众筹用时
     */
    public void updateZcUseTime() {
        List<Project> projects = projectService.getInitUseTimeData();
        long now = DateUtils.getTodayDate().getTime();
        for (Project project : projects) {
            try {
                long createDate = project.getCreateDate().getTime();
                Project p = new Project();
                p.setId(project.getId());
                if (project.getIsSuccess() == 0) {
                    p.setUseTime(now - createDate);
                } else if (project.getIsSuccess() == 1) {
                    if (project.getLastSupportDate() != null) {
                        List<SupportTransfer> transferList = supportTransferService.getByTargetProId(project.getId());
                        //如果该project不是转移过来的  才更新useTime
                        if (transferList.size() < 1) {
                            p.setUseTime(project.getLastSupportDate().getTime() - createDate);
                        } else {
                            p.setUseTime(Long.valueOf(60000));
                        }
                    }
                }
                if (p.getUseTime() != null) {
                    projectService.update(p);
                }
            } catch (Exception e) {
                logger.error("循环更新众筹用时异常：projectId--" + project.getId(), e);
                continue;
            }
        }
    }

    /**
     * 检查文件是否存在
     *
     * @param zipUrl 链接
     * @return 是否存在（true/fase）
     */
    public boolean checkFileIsExits(String zipUrl) {
        File file = new File(baseDir + zipUrl);
        if (file.exists()) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 众筹自动报名
     *
     * @param activity      活动
     * @param source        资源众筹
     * @param counterfoilId
     */
    public String apply(Activity activity, Project source, String counterfoilId) {
        ApplyParameter parameter = new ApplyParameter();
        parameter.setActivityId(activity.getId());
        parameter.setMemberId(source.getAuthorId());
        Member member = memberService.get(source.getAuthorId());
        parameter.setRealname(member.getRealname());
        parameter.setMobile(member.getMobile());
        parameter.setCompany(member.getCompany());
        parameter.setTitle(member.getJobTitle());
        parameter.setDeclaration(source.getDeclaration());
        parameter.setStyle(source.getStyle());
        parameter.setProjectTitle(activity.getTitle());
        String projectId = projectApplyService.apply(parameter, counterfoilId);

        // 更新机构统计数
        memberMerchantDetailBizService.updateApplyNum(activity.getMember());

        // 更新合作商统计数
        memberCopartnerDetailBizService.updateApplyNum(projectId);

        try {
            // 会员统计数
//			memberPersonalCountBizService.updateCrowdfundNum(activity.getMember(), source.getAuthorId(), true);
            PartnerMember partnerMember = partnerMemberService.findByPartnerAndMember(activity.getMember(), source.getAuthorId());
            memberPersonalCountBizService.countOne(partnerMember);
        } catch (Exception e) {
            logger.error("众筹自动报名统计会员数异常", e);
        }

        // 生成二维码
        try {
            String filePath = fileBizService.getUploadCIPath("crowdfund", source.getAuthorId());
            String content = "project/project_detail.html?id=" + projectId;
            CrowdfundEvent crowdfundEvent = crowdfundEventService.findByProjectId(projectId);
            if (null != crowdfundEvent && YesNoStatus.YES.getCode().equals(crowdfundEvent.getIsMultiple())) {
                content = "project/project_multi_detail.html?id=" + projectId;
            }
            String previewPicUrl = fileBizService.uploadCloudOut(projectId, filePath, content, activity.getMember());
            if (previewPicUrl == null) {
                logger.error("生成众筹详情二维码异常——众筹项目id= " + activity.getId() + "——众筹id=" + projectId);
            }
        } catch (Exception e) {
            logger.error("生成众筹详情二维码异常", e);
        }
        return projectId;
    }

    public Map<String, Object> getDistributionData(String relationId) {
        Map<String, Object> map = Maps.newHashMap();
        return map;
    }

    /**
     * 查询活动下的众筹
     *
     * @param projectWithAuthor 众筹信息
     * @param page              分页参数
     * @return 众筹列表
     */
    public List<ProjectForActivityOutput> projectTransferForActivityList(ProjectWithAuthor projectWithAuthor, Page page, String publisher) {
        String memberId = RealmUtils.getCurrentUser().getId();
        projectWithAuthor.setDistribution(true);
        List<ProjectWithAuthor> projectWithAuthorList = projectService.listTransferWithAuthorPage(projectWithAuthor, page);
        List<ProjectForActivityOutput> projectForActivityOutputList = LangUtils.transform(projectWithAuthorList, new Function<ProjectWithAuthor, ProjectForActivityOutput>() {
            @Override
            public ProjectForActivityOutput apply(ProjectWithAuthor projectWithAuthor) {
                ProjectForActivityOutput output = transform(projectWithAuthor);
/*				String codeUrl = getQrCodeUrl(projectWithAuthor.getAuthorId(),projectWithAuthor.getId());
				String url = getUrl(projectWithAuthor.getId());
				output.setQrCodeUrl(codeUrl);
				output.setUrl(url);*/
                //替换手机号
                String phone = memberBizService.replacePhone(memberId, projectWithAuthor.getAuthorMobile());
                projectWithAuthor.setAuthorMobile(phone);

                String filePath = fileBizService.getUploadCIPath("crowdfund", projectWithAuthor.getAuthorId());
                String qrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + projectWithAuthor.getId());
                String url = getUrl(projectWithAuthor.getId(), YesNoStatus.NO.getCode());
                output.setQrCodeUrl(qrCodeUrl);
                output.setUrl(url);
                return output;
            }
        });
        return projectForActivityOutputList;
    }

    /**
     * @param id         活动id
     * @param relationId 分销关系id
     * @param page       分页参数
     * @return
     * @Author yifeng
     * @Description 根据分销关系查询众筹列表
     * @Date 9:35 2019/3/27
     **/
    public Map<String, Object> listForDistributorCommonActivity(String id, String relationId, Page page) {
        Map<String, Object> map = Maps.newHashMap();
        page.setLimit(20);
        Activity activity = activityService.get(id);
        map.put("activity", activity);
        //众筹金额
        float actualAmount = activityBizService.actualAmountForTargetId(id);
        map.put("actualAmount", actualAmount);
        List<ProjectForActivityOutput> projectForActivityOutputList = listForDistributorId(relationId, page);

        Integer crowdfundNum = projectService.sizeForTargetId(id);
        Integer directPayNum = projectService.directPaySizeForTargetId(id, null, 1);

        DistributorRelation distributorRelation = distributorRelationService.get(relationId);
        Member member = memberService.get(distributorRelation.getDistributorId());

        Integer transferNum = supportTransferService.getShiftToPeopleTotal(activity.getId());
        map.put("transferNum", transferNum == null ? 0 : transferNum);

        map.put("list", projectForActivityOutputList);
        map.put("crowdfundNum", crowdfundNum);
        map.put("directPayNum", directPayNum);
        map.put("page", page);
        map.put("name", member.getRealname());
        map.put("relationId", relationId);
        return map;
    }

    /**
     * 事项联合发起项目
     *
     * @param relationId 关系编号
     * @param eventId    事件编号
     * @param page       分页参数
     * @return 交互数据
     */
    public Map<String, Object> listForDistributorCommonEvent(String eventId, String relationId, Page page) {
        Map<String, Object> map = Maps.newHashMap();
        page.setLimit(20);

        //众筹金额
        List<ProjectForActivityOutput> projectForActivityOutputList = listForDistributorId(relationId, page);

        Integer representNum = distributorRelationService.countForEvent(eventId);
        Integer projectNum = projectService.countForEvent(eventId);
        Integer directPayNum = projectService.dpCountForEvent(eventId, 1);
        DistributorRelation distributorRelation = distributorRelationService.get(relationId);
        Member author = memberService.get(distributorRelation.getDistributorId());

        map.put("eventId", eventId);
        map.put("representNum", representNum);
        map.put("projectNum", projectNum);
        map.put("directPayNum", directPayNum);
        map.put("list", projectForActivityOutputList);
        map.put("page", page);
        map.put("name", author.getRealname());
        map.put("relationId", relationId);
        CrowdfundEvent crowdfundEvent = crowdfundEventService.get(eventId);
        map.put("crowdfundEvent", crowdfundEvent);
        return map;
    }

    /**
     * 绘制众筹海报
     *
     * @param projectId 众筹id
     * @return 文件字节数组
     */
    public byte[] paintProjectPoster(String projectId) {
        CrowdfundEvent crowdfundEvent = crowdfundEventService.findByProjectId(projectId);
        ProjectPosterOutput posterOutput = getPaintPosterData(projectId, crowdfundEvent);
        if (posterOutput == null) {
            return null;
        }

        try {
            ImageIO.read(new URL(posterOutput.getQrcodeUrl()));
        } catch (Exception e) {
            try {
                String filePath = fileBizService.getUploadCIPath(posterOutput.getPublisherId(), "zcActivity");
                if (YesNoStatus.NO.getCode().equals(crowdfundEvent.getIsMultiple())) {
                    /*** 众筹项目详情二维码 ***/
                    String xqFileName = "detail_" + posterOutput.getActivityId();
                    String detailContent = "project/target_client_detail.html?id=" + posterOutput.getActivityId();
                    String qrcodeUrl = fileBizService.uploadCloudOut(xqFileName, filePath, detailContent, posterOutput.getPublisherId());
                    posterOutput.setQrcodeUrl(qrcodeUrl);
                } else if (YesNoStatus.YES.getCode().equals(crowdfundEvent.getIsMultiple())) {
                    /*** 众筹项目详情二维码 ***/
                    String xqFileName = "detail_" + posterOutput.getActivityId();
                    String detailContent = "project/target_multi_detail.html?id=" + posterOutput.getActivityId();
                    String qrcodeUrl = fileBizService.uploadCloudOut(xqFileName, filePath, detailContent, posterOutput.getPublisherId());
                    posterOutput.setQrcodeUrl(qrcodeUrl);
                }
            } catch (Exception ex) {
                logger.error("众筹项目二维码生成异常", ex);
            }
        }

        return paintProjectPosterBiz.projectPosterUploadCI(posterOutput);
    }

    /**
     * 获取绘制海报的数据
     *
     * @param projectId 众筹id
     * @return
     */
    public ProjectPosterOutput getPaintPosterData(String projectId, CrowdfundEvent crowdfundEvent) {
        try {
            ProjectPosterOutput posterOutput = new ProjectPosterOutput();
            posterOutput.setProjectId(projectId);
            Project project = projectService.get(projectId);
            // 支持人数
            posterOutput.setSupportNum(project.getFavorerNum());
            // 众筹者
            Member author = memberService.get(project.getAuthorId());
            if (author == null) {
                throw new BusinessException(PartyCode.IS_NO_DATA, "用户为空");
            }
            // 昵称
            posterOutput.setNickName(author.getRealname());
            // 公司
            posterOutput.setCompany(author.getCompany());
            // 头像
            posterOutput.setLogo(author.getLogo());
            posterOutput.setAuthorId(author.getId());

            TargetProject targetProject = targetProjectService.findByProjectId(projectId);
            if (targetProject == null) {
                throw new BusinessException(PartyCode.IS_NO_DATA, "项目为空");
            }
            String targetId = targetProject.getTargetId();
            Activity activity = activityService.get(targetId);
            if (activity == null) {
                throw new BusinessException(PartyCode.IS_NO_DATA, "项目为空");
            }
            // 金额
            posterOutput.setMoney(project.getActualAmount().doubleValue());
            // 标题
            posterOutput.setProjectTitle(activity.getTitle());
            // 海报
            posterOutput.setProjectPic(activity.getPic());
            // 二维码
            String filePath = fileBizService.getUploadCIPath(activity.getMember(), "zcActivity");
            String detailFileName = "detail_" + activity.getId();
            String detailQrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + detailFileName);
            posterOutput.setQrcodeUrl(detailQrCodeUrl);
            if (YesNoStatus.NO.getCode().equals(crowdfundEvent.getIsMultiple())) {
                // 开始时间
                posterOutput.setStartDate(DateUtils.formatDate(activity.getStartTime(), "yyyy.MM.dd"));
                // 地点Map
                Map<String, String> addressMap = Maps.newHashMap();
                String address = activityService.getShowAddressMap(activity, addressMap);
                posterOutput.setPlaceMap(addressMap);
                posterOutput.setPlace(address);
            }
            // 发布者
            MemberGroup publisher = memberGroupService.get(activity.getMember());
            if (publisher != null) {
                posterOutput.setOrgName(publisher.getRealname());
            }
            posterOutput.setPublisherId(activity.getMember());
            posterOutput.setActivityId(activity.getId());
            // 众筹用时
            posterOutput.setIsMultiple(crowdfundEvent.getIsMultiple());
            if (YesNoStatus.YES.getCode().equals(crowdfundEvent.getIsMultiple())) {
                List<ProjectGradation> projectGradations = projectGradationService.getSuccessListForProjectId(projectId);
                Long diffTime = 0L;
                Double price = 0d;
                for (ProjectGradation projectGradation : projectGradations) {
                    diffTime += projectGradation.getUseTime();
                    price = BigDecimalUtils.add(projectGradation.getTargetAmount(), price);
                }

                long oneMonthMs = 30L * 24L * 60L * 60L * 1000L;
                long oneDayMs = 24L * 60L * 60L * 1000L;
                long oneHourMs = 60 * 60 * 1000;
                long oneMinMs = 60 * 1000;

                long month = diffTime / oneMonthMs;
                long monthAll = month * oneMonthMs;

                long day = (diffTime - monthAll) / oneDayMs;
                long dayAll = day * oneDayMs;

                posterOutput.setUseTimeMonth(month);
                posterOutput.setUserTimeDay(day);
                posterOutput.setMoney(BigDecimalUtils.round(price, 2));
                posterOutput.setSuccessCount(projectGradations.size());

                if (month <= 0 && day <= 0) {
                    posterOutput.setUserTimeDay(1L);
                }
            } else {
                Long diffTime = project.getUseTime();

                long month = diffTime / (30 * 24 * 60 * 60 * 1000);
                long day = diffTime / (24 * 60 * 60 * 1000);
                long hour = (diffTime / (60 * 60 * 1000) - day * 24);
                long min = ((diffTime / (60 * 1000)) - day * 24 * 60 - hour * 60);

                posterOutput.setUserTimeDay(day);
                posterOutput.setUserTimeHour(hour);
                posterOutput.setUserTimeMinute(min);

                if (day <= 0 && hour <= 0 && min <= 0) {
                    posterOutput.setUserTimeMinute(1L);
                }
            }
            return posterOutput;
        } catch (BusinessException e) {
            logger.error("获取绘制海报数据异常BusinessException", e);
            return null;
        } catch (Exception e) {
            logger.error("获取绘制海报数据异常Exception", e);
            return null;
        }
    }

    /**
     * 获取众筹成功海报
     *
     * @param projectId 众筹编号
     * @return 众筹海报图片路径
     */
    public String getProjectPoster(String projectId) {
        Project project = projectService.get(projectId);
        CrowdfundEvent crowdfundEvent = crowdfundEventService.findByProjectId(projectId);

        if (null != crowdfundEvent) {
            if (YesNoStatus.NO.getCode().equals(crowdfundEvent.getIsMultiple())) {
                if (!YesNoStatus.YES.getCode().equals(project.getIsSuccess())) {
                    throw new BusinessException(110, "该众筹状态不是成功的");
                }
            }
        }
        String filePath = String.format("%s/%s/", project.getAuthorId(), "zcPoster");

        byte[] bytes = paintProjectPoster(projectId);
        if (bytes == null) {
            throw new BusinessException(666, "获取海报数据异常");
        }
        String resourceUrl = cosBizService.getPreviewPictureUrl(filePath + projectId, "png");
        return resourceUrl;
    }

    public String getNewYearPoster(Project project) {

        String proejct_id = project.getId();
        String filePath = String.format("%s/%s/", project.getAuthorId(), "newYearPoster");
        String filename = project.getId();

        Activity activity = activityService.findByProjectId(project.getId());

        if (null != activity && 1 == activity.getIsCustomPoster()) {
            //设置了项目自定义海报
            filename = MD5Util.getMD5(activity.getNetworkImagePath() + project.getId());
        } else {
            CrowdfundEvent ce = crowdfundEventService.findByProjectId(project.getId());
            if (null != ce && 1 == ce.getIsCustomPoster()) {
                //设置了主题自定义海报
                filename = MD5Util.getMD5(ce.getNetworkImagePath() + project.getId());
            }

        }

        String resourceUrl = cosBizService.getPreviewPictureUrl(filePath + filename, "png");
        boolean ble = false;
        String resourceUrl_to = "";
        try {
            ImageIO.read(new URL(resourceUrl));
        } catch (IOException e) {
            ble = true;
            try {
                resourceUrl_to = this.paintNewYearPoster(proejct_id, filename);
            } catch (Exception e1) {
                logger.error("新年宣传海报生成异常", e);
            }
        } finally {
            if (ble) {
                resourceUrl = resourceUrl_to;
            }
            return resourceUrl;
        }
    }

    public String newYearPosterDemo(String networkImagePath, String memberId) {

        // logo图路径
        String filePath = String.format("%s/%s/", memberId, "newYearPoster"),
                filename;
        if (StringUtils.isEmpty(networkImagePath)) {
            filename = MD5Util.getMD5(memberId);
        } else {
            filename = MD5Util.getMD5(networkImagePath);
        }
        String resourceUrl = cosBizService.getPreviewPictureUrl(filePath + filename, "png");
        boolean ble = false;
        String resourceUrl_to = "";
        byte[] bytes = null;
        try {
            ImageIO.read(new URL(resourceUrl));
        } catch (IOException e) {
            ble = true;
            try {
                ProjectPosterOutput posterOutput = new ProjectPosterOutput();
                posterOutput.setNetworkImagePath(networkImagePath);
                //posterOutput.setLogo(member.getLogo());
                bytes = paintProjectPosterBiz.newYearPoster(posterOutput);
                try {
                    resourceUrl_to = String.format("/%s/%s/", memberId, "newYearPoster");
                    resourceUrl_to = paintProjectPosterBiz.PosterUploadCI(filename, resourceUrl_to, bytes);
                } catch (Exception e2) {
                    logger.error("新年宣传海报上传腾讯云异常", e2);
                }
            } catch (Exception e1) {
                logger.error("新年宣传海报生成异常", e1);
            }
        } finally {
            if (ble) {
                resourceUrl = resourceUrl_to;
            }
            return resourceUrl;
        }
    }

    /**
     * @Description: 获取新年宣传海报
     * @Param:
     * @return:
     * @Author: Hua Qunhao
     * @Date: 2019-01-23-0023
     */
    public String paintNewYearPoster(String projectId, String fileName) throws Exception {

        String posterPath = "";
        byte[] bytes = null;
        ProjectPosterOutput posterOutput = new ProjectPosterOutput();
        posterOutput.setProjectId(projectId);

        Project project = projectService.get(projectId);
        Activity activity = activityService.findByProjectId(projectId);
        Member member = memberService.get(project.getAuthorId());
        CrowdfundEvent ce = crowdfundEventService.findByProjectId(projectId);

        posterOutput.setAuthorId(project.getAuthorId());
        posterOutput.setLogo(member.getLogo());

        String networkImagePath = "";
        if (StringUtils.isNotEmpty(ce.getNetworkImagePath())) {
            networkImagePath = ce.getNetworkImagePath();
        }
        if (StringUtils.isNotEmpty(activity.getNetworkImagePath())) {
            networkImagePath = activity.getNetworkImagePath();
        }
        posterOutput.setNetworkImagePath(networkImagePath);

        try {
            /*** 个人众筹项目详情二维码 ***/
            String filePath = fileBizService.getUploadCIPath("crowdfund", posterOutput.getAuthorId());
            String qrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + posterOutput.getProjectId());
            posterOutput.setPersonalQrCodeUrl(qrCodeUrl);

            bytes = paintProjectPosterBiz.newYearPoster(posterOutput);

            try {
                posterPath = String.format("/%s/%s/", posterOutput.getAuthorId(), "newYearPoster");
                posterPath = paintProjectPosterBiz.PosterUploadCI(fileName, posterPath, bytes);
            } catch (Exception e) {
                logger.error("新年宣传海报上传腾讯云异常", e);
            }


        } catch (Exception e) {
            //生成众筹详情二维码异个人二维码
            try {
                String filePath = fileBizService.getUploadCIPath("crowdfund", posterOutput.getAuthorId());
                String content = "project/project_detail.html?id=" + projectId;
                if (null != ce && YesNoStatus.YES.getCode().equals(ce.getIsMultiple())) {
                    content = "project/project_multi_detail.html?id=" + projectId;
                }
                String previewPicUrl = fileBizService.uploadCloudOut(projectId, filePath, content, posterOutput.getAuthorId());
                if (previewPicUrl == null) {
                    logger.error("生成众筹详情二维码异个人二维码");
                }
            } catch (Exception e2) {
                logger.error("生成众筹详情二维码异个人二维码", e2);
            }

            logger.error("新年宣传海报生成异常", e);
        }


        return posterPath;
    }
}
